package com.lsk.netdisk.file.controller;

import com.lsk.netdisk.common.response.aspect.annotation.JsonReturn;
import com.lsk.netdisk.file.helpers.CloudHelper;
import com.lsk.netdisk.file.helpers.FileHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;

@Slf4j
@RestController
public class Controller {
	@Autowired
	private CloudHelper cloudHelper;

	@GetMapping("/ls")
	@JsonReturn
	public Object ls(Integer dirID, String token) {
		Integer uid = cloudHelper.getCurrentUserID(token);
		if (dirID == -1) {
			dirID = FileHelper.getWorkingDirId(uid);
		}
		return FileHelper.ls(dirID, uid);
	}

	@GetMapping("/createUserDir")
	public void register(String token, String username) {
		Integer currentUserID = cloudHelper.getCurrentUserID(token);
		Integer dirID = FileHelper.mkUserDir(username, currentUserID);
		FileHelper.setWorkingDir(dirID, currentUserID);
	}

	@GetMapping("/mkdir")
	public void mkdir(String name, Integer parent, @CookieValue("token") String token) {
		Integer currentUserID = cloudHelper.getCurrentUserID(token);
		if (!FileHelper.getDirName(parent).equals("/")) {
			FileHelper.setWorkingDir(parent, currentUserID);
		}
		FileHelper.mkdir(name, currentUserID);
	}

	@PostMapping("/uploadFile")
	@JsonReturn
	public Object uploadFile(@CookieValue("token") String token, MultipartFile file) throws Exception {
		FileHelper.uploadFile(cloudHelper.getCurrentUserID(token), file);
		return "Success";
	}

	@GetMapping("/cd")
	@JsonReturn
	public Object cd(@CookieValue("token") String token, Integer dirID) {
		FileHelper.cd(dirID, token);
		return "Success";
	}
	@GetMapping("/downloadFile")
	public void downloadFile(@CookieValue("token") String token, Integer fileId, HttpServletResponse resp){
		File file = FileHelper.downloadFile(cloudHelper.getCurrentUserID(token),fileId);
		OutputStream os = null;
		InputStream is = null;
		try{
			resp.setContentType("application/force-download");
			resp.addHeader("Content-Disposition", "attachment;fileName=" + file.getName());
			os = resp.getOutputStream();
			is = new FileInputStream(file);
			BufferedInputStream bis = new BufferedInputStream(is);
			byte[] buffer = new byte[1024];
			int i = bis.read(buffer);
			while(i != -1) {
				os.write(buffer, 0, i);
				i = bis.read(buffer, 0, i);
			}
		}catch (Exception e){
			log.error("Cannot download",e);
		}finally {
			try {
				is.close();
			}catch (Exception e){
				log.error("Cannot close Input stream",e);
			}
			try {
				os.close();
			}catch (Exception e){
				log.error("Cannot close output stream",e);
			}
			file.delete();
		}
	}
}